<template>
  <div id="dispose">
    <v-title title="汽车管理看板权限配置"></v-title>
    <el-row>
        <el-col :xs="24" :sm="24" :lg="6" class="form">
            <el-input  v-model="search_name" placeholder="搜索姓名，LDAP账号"><el-button type="success" size="mini">搜索</el-button></el-input>
            <el-button class="search" @click="getTableResult" type="primary" size="mini">搜索</el-button>                       
        </el-col>
    </el-row>

    <div class="table">
      <el-table
        class="marT"          
        :border="true"
        :header-cell-style="{background:'rgb(50, 65, 90)'}"
        :data="list"                      
        style="width: 100%"
        >
          <el-table-column
            label="姓名"
            align="center"
            prop="chinese_name">     
          </el-table-column>
          <el-table-column
            label="LDAP"
            align="center"
            prop="ldap_account">     
          </el-table-column>

          <el-table-column
            label="配置权限"
            align="center"
            >    
            <template slot-scope="scope">
              <div v-if="!scope.row.editStatus">{{ scope.row.car_config_perm ? '有': '无' }}</div>
              <div v-else>
                <el-select v-model="scope.row.car_config_perm">
                  <el-option
                    v-for="item in permOptions"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="看板权限"
            align="center"
            >    
            <template slot-scope="scope">
              <div v-if="!scope.row.editStatus">{{ scope.row.car_entry_perm ? '有': '无' }}</div>
              <div v-else>
                <el-select v-model="scope.row.car_entry_perm">
                  <el-option
                    v-for="item in permOptions"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="导出权限"
            align="center"
            >    
            <template slot-scope="scope">
              <div v-if="!scope.row.editStatus">{{ scope.row.car_export_perm ? '有': '无' }}</div>
              <div v-else>
                <el-select v-model="scope.row.car_export_perm">
                  <el-option
                    v-for="item in permOptions"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="周报权限"
            align="center"
            >     
            <template slot-scope="scope">
              <div v-if="!scope.row.editStatus">
                {{ scope.row.week_report_perm.join(',') }}                
              </div>
              <div v-else>
                <el-select
                  v-model="scope.row.week_report_perm"
                  multiple
                  filterable
                  remote                  
                  placeholder="请输入项目名称"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @blur="blur" 
                  @change="change(scope.$index, $event)"               
                  >
                  <el-option
                    v-for="item in options"
                    :key="item"
                    :label="item"
                    :value="item"
                    >
                      <span style="float: left">{{ item }}</span>
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>

          <el-table-column              
                label="操作"
                align="center"             
            >
                <template slot-scope="scope">
                <div>
                    <el-button size="mini" v-show="!scope.row.editStatus" @click="toEdit(scope.row, scope.$index,)" type="primary" round>编辑</el-button>
                    <el-button class="button" size="mini" @click="saveResult(scope.$index)" v-show="scope.row.editStatus" type="success" round>保存</el-button>
                    <el-button class="button" size="mini" @click="cancel(scope.$index)" v-show="scope.row.editStatus" type="warning" round>取消</el-button>
                </div>
                </template>
            </el-table-column>
      </el-table>
      <el-pagination class="marT"
          background  
          :page-size="baseSize"                                   
          @current-change="baseCurrentChange"
          :current-page="baseCurrent"
          @size-change="baseSizeChange"                              
          layout="total, prev, pager, next, jumper"
          style="text-align: left"
          :total="baseTotal">
        </el-pagination>
    </div>
  </div>
</template>

<script>
  import VTitle from '@/views/sys/internetThings/title'
  import VCondition from '@/views/data/carDispose/group'
  import { mapState } from 'vuex'
  import http from '@/views/sys/axios'
  // import VDialog from '@/views/qa/dialog'
  // import VButton from './button'

  export default {
    name: 'Dispose',
    components: {
      VTitle,
      VCondition,
      // VDialog,
      // VButton
    },
    data() {
      return {
        search_name: '',
        list: [],
        // base: [],
        url: `/api/data_summary/car/project/file/upload`,
        baseCurrent: 1,
        baseTotal: 0,
        baseSize: 10,
        options: [],
        fileStatus: true,
        fileList: [],
        permOptions: [
          {
            value: true,
            label: '有'
          },
          {
            value: false,
            label: '无'
          }
        ],
        cache: [],        
        loading: false
        // dialogTableVisible: false,
        // dialogData: [],
        // tableListLabel: [
        //   {
        //       label: '项目',
        //       param: 'project_name',
        //       align: 'center'
        //   },
        //   {
        //       label: '更新模块',
        //       param: 'dimension',
        //       align: 'center'
        //   }, 
        //   {
        //       label: '更新项',
        //       param: 'examine_item',
        //       align: 'center'
        //   },
        //   {
        //       label: '修改者',
        //       param: 'operator',
        //       align: 'center'
        //   },
        //   {
        //       label: '修改日志',
        //       param: 'operator_log',
        //       align: 'center'
        //   },
        //   {
        //       label: '更新时间',
        //       param: 'create_time',
        //       align: 'center'
        //   }                                           
        // ]
      }
    },
    computed: {
      ...mapState({
        dispose: state => state.conditions.dispose
      })
    },
    mounted() {
      this.getTableResult()
      // if(this.dispose.projectIdList.length) {
      //   this.getLookResult()
      // }
    },
    methods: {
      toEdit(row,index) {  
        row.editStatus = true
        this.$set(this.list, index, row)
        console.log(this.list)
      },
      cancel(index) {
        this.list[index].editStatus = false 
        this.getTableResult()   
      },
      async handUploadFile(content) {
        const { file } = content              
        let formData = new FormData();     
        formData.append('file',content.file);
        formData.append('name',file.name);
        http.post(content.action, formData).then(res => {
          if(res.code == 200) {
            content.onSuccess('文件上传成功')
          } else {
            content.onError(`文件上传失败,${res.msg}`)
          }
        }).catch(err => {
          throw err
        })
      },
      handleSuccess(res) {
        if(res) {
          this.$message({
            message: res,
            type: 'success'
          });
        }      
      },
      erroring(err) {
        if(err) {
          this.$message({
            message: err,
            type: 'error'
          });
        }
      },
      handleRemove(file) {
        this.fileList = []
      },
      beforeAvatarUpload(file) {
        let size = file.size / 1024
        this.fileStatus = true
        
        if (size > 2000) {
          this.$message({
            message: '导入的Excel表不能大于2M!',
            type: 'error'
          });
          this.fileStatus = false
          return
        }

        let name = file.name;
        let fileName = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
        if (fileName != "xlsx" && fileName != "xls") {
          this.$message({
            message: '请选择正确得Excel格式文件上传!',
            type: 'error'
          }); 
          this.fileStatus = false
          return
        }   
      },
      toDate(num) {
        num = Number(num)
        switch (num) {
          case 1:
            return '每周一';
            break;
          case 2:
            return '每周二';
            break;
          case 3:
            return '每周三';
            break;
          case 4:
            return '每周四';
            break;
          case 5:
            return '每周五';
            break;
          case 10:
            return '每月';
            break;
          default:
            return '';
            break;
        } 
      },
      baseCurrentChange(val) {
        this.baseCurrent = val
        this.getTableResult()
      },
      baseSizeChange(val) {
        this.baseSize = val
      },
      change(index, val) {
        const obj = this.cache.filter(item => item.value === val[val.length - 1])
        const week_report_perm = [...this.list[index].week_report_perm, ...obj]
        this.$set(this.list[index], 'week_report_perm', week_report_perm)
      },
      generate(arr) {
        if(arr.length) {
          const list = arr.map(item => item.label)
          return list
        } else {
          return []
        }
      },
      blur() {
        this.options = []
      },
      async remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          this.options = []
          this.getStateResult(query)
        } else {
          this.options = [];
        }
      },
      getStates(name) {
        return http.get(`/api/base/get_project_name?query=${name}`)
      },
      async getStateResult(name) {
        try {
          const { code, project_list } = await this.getStates(name)
          if(code === 200) {
            this.loading = false
            this.options = project_list
            this.cache = project_list
          }
        } catch (err) {
          throw new Error(err)
        }
      },
      getTable() {
        return http.get(`/api/data_summary/car/project/perm?condition=${this.search_name}&page=${this.baseCurrent}`)
      },
      async getTableResult() {
        try {
          const { code, count, result } = await this.getTable()
          if(code === 200) {
            this.list = result
            console.log(result)
            this.baseTotal = count
            this.list = this.list.map(item => {
              item['editStatus'] = false
              item['week_report_perm'] = item['week_report_perm'] == '' ? []:item['week_report_perm']
              return item
            })
            // let arr = this.list
          }
        } catch (err) {
          throw new Error(err)
        }
      },
      save(index) {
        let data = this.list[index]
        return http.post(`/api/data_summary/car/project/perm`, data)
      },
      async saveResult(index) {
        try {
          const { code, msg } = await this.save(index)
          if(code === 200) {
            //this.cancel(index)
            this.$message({
              showClose: true,
              message: '保存成功!',
              type: 'success'
            });
            this.getTableResult()
          } else {
            this.$message({
              showClose: true,
              message: msg,
              type: 'error'
            });
          }
        } catch(err) {
          this.list[index].editStatus = false
          throw new Error(err)
        }
      }
    }
    // watch: {
    //   dispose: {
    //     handler: function(newVal) {
    //       if(newVal) {
    //         this.getLookResult()
    //       }
    //     },
    //     deep: true
    //   },
    //   dialogTableVisible(newVal) {
    //     if(!newVal) {
    //       this.dialogData = []
    //     }
    //   }
    // }
  }
</script>

<style lang="scss" scoped>
  @import '../../../../assets/common/common.scss';
  /deep/ .el-table thead {
    color: #fff;
  }
  /deep/ .el-table th.gutter{
    display: table-cell!important;
  }
  #dialog >>> .el-table thead{
    color: #909399;
  }
  .loader{
    margin: 15px 0px;
    position: absolute;
    right: 175px;
    top: -16px;
  }
  #dispose{
    padding: 32px;
    background-color: rgb(240, 242, 245);
    position: relative;
    .btn-group{
      text-align: right;
      position: relative;
      .title{
        position: absolute;
        left: 0;
      }
    }
    .details{
      cursor: pointer;
      color: rgb(50, 65, 90);
      text-decoration: underline;
    }
  }
  .marT{
      margin-top: 20px;
  }
.form{
    position: relative;
    .search{
        position: absolute;
        top: 0;
        right: 0;
        height: 100%;
    }
}
</style>